package cn.xy.basic.interceptor;

import cn.xy.basic.anno.PreAuthorize;
import cn.xy.basic.jwt.JwtUtils;
import cn.xy.basic.jwt.LoginResult;
import cn.xy.basic.jwt.Payload;
import cn.xy.basic.jwt.RsaUtils;
import cn.xy.system.mapper.PermissionMapper;
import cn.xy.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取 U-TOKEN
        String token = request.getHeader("U-TOKEN");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if(StringUtils.hasLength(token)){
            //3.根据U-TOKEN从redis中获取登录信息
//            Object loginTmp = redisTemplate.opsForValue().get(token);

            //由于业务层已经修改为返回jwt串了，所以后置拦截器也需要修改
            //解密jwt串得到登录人的信息和登录人权限
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥进行解密
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();

            if(loginResult!=null){
                //增加判断是否为员工，
                Logininfo logininfo = loginResult.getLogininfo();
                if(logininfo.getType()==0){
                    //为员工,需要校验权限
                    HandlerMethod method = (HandlerMethod) handler;
                    //得到当前的请求资源url
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if(annotation != null){
                        //获取sn的值
                        String currentSn = annotation.value();
                        //根据logininfoid查询数据库，查询出当前员工的权限有哪些
//                        List<String> permissions = permissionMapper.loadPermissionByLoginInFoId(logininfo.getId());
                        //判断permissions是否包含url，包含的话就放行，不包含则说明没有此权限，不放。
                        if(!loginResult.getPermissions().contains(currentSn)){
                            //不包含，权限不足
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                        //放行
                    }
                }
                //不需要redis了，
//                redisTemplate.opsForValue().set(token,loginTmp,30,TimeUnit.MINUTES);
                return true;//登陆了 放行
            }

        }
        //2.滚去登录

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行

    }
}
